from sqlalchemy.orm import Session
from models.user import User
from schemas.user import UserCreate
from utils.security import hash_password, verify_password, create_jwt_token

def register_user(db: Session, user_data: UserCreate):
    """用户注册"""
    # 检查用户名是否存在
    existing_user = db.query(User).filter(User.username == user_data.username).first()
    if existing_user:
        return None, "用户名已存在"

    # 创建新用户
    new_user = User(
        username=user_data.username,
        password_hash=hash_password(user_data.password)
    )
    db.add(new_user)
    db.commit()
    db.refresh(new_user)
    return new_user, None

def login_user(db: Session, username: str, password: str):
    """用户登录"""
    user = db.query(User).filter(User.username == username).first()
    if not user:
        return None, "用户不存在"
    
    if not verify_password(password, user.password_hash):
        return None, "密码错误"

    # 生成JWT令牌
    token = create_jwt_token({"user_id": user.id, "username": user.username})
    return token, None

def get_user_by_id(db: Session, user_id: int):
    """根据ID获取用户"""
    return db.query(User).filter(User.id == user_id).first()

def update_user(db: Session, user: User, username: str = None, password: str = None):
    """更新用户信息"""
    if username:
        # 检查新用户名是否已被使用
        existing_user = db.query(User).filter(User.username == username, User.id != user.id).first()
        if existing_user:
            return None, "用户名已被使用"
        user.username = username
    
    if password:
        user.password_hash = hash_password(password)
    
    db.commit()
    db.refresh(user)
    return user, None
